<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" :src="avatar" alt="" />
      <img v-else src="../../../assets/images/avatar.jpg" alt="" />
      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          @change="changeHandler"
          type="file"
          ref="inputImage"
          style="display: none"
          accept="image/*"
        />
        <el-button
          type="primary"
          @click="$refs.inputImage.click()"
          class="btn btn"
          icon="el-icon-plus"
          >选择图片</el-button
        >
        <el-button
          @click="upAvatarHandler"
          type="success"
          icon="el-icon-upload"
          :disabled="!avatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    changeHandler (e) {
      //  console.log(e.target.files[0])
      //   使用FileReader来读取文件信息
      // 1.创建FileReader对象
      const fr = new FileReader()
      //   2.调用redAsDataURL将File对象转换为base64字符串
      // dataUrl:base64格式的链接
      fr.readAsDataURL(e.target.files[0])
      // 3.因为读取是异步操作，所以要用事件来获取结果
      fr.onload = (e) => {
        this.avatar = e.target.result
      }
    },
    async upAvatarHandler () {
      const { data: res } = await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      if (res.code === 0) {
        this.$store.dispatch('getUserInfo')
        return this.$message({ type: 'success', message: res.message })
      }
      return this.$message({ type: 'error', message: res.message })
    }
  }
  // 将图片转成base64
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
</style>
